package com.example.yogurtsystem.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yogurtsystem.common.PageResult;
import com.example.yogurtsystem.dto.DrinkDto;
import com.example.yogurtsystem.dto.SaveOrUpdateDto;
import com.example.yogurtsystem.entity.Drinks;
import com.example.yogurtsystem.entity.User;
import com.example.yogurtsystem.entity.UserRecord;
import com.example.yogurtsystem.exception.ServiceException;
import com.example.yogurtsystem.mapper.DrinksMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yogurtsystem.entity.UserRecord;
import com.example.yogurtsystem.mapper.UserMapper;
import com.example.yogurtsystem.mapper.UserRecordMapper;
import com.example.yogurtsystem.service.UserRecordService;
import com.example.yogurtsystem.utils.PageUtil;
import com.example.yogurtsystem.utils.TableTagBean;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author ZWYZY
 * @since 2021/8/15
 */
@Service
public class UserRecordServiceImpl extends ServiceImpl<UserRecordMapper,UserRecord> implements UserRecordService {
    private final Logger log = LoggerFactory.getLogger(getClass());
    @Resource
    private UserRecordMapper userRecordMapper;
    @Resource
    private DrinksMapper drinksMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public PageResult<?> selectUserRecordByLimit(TableTagBean ttb) {
        int pageNum = ttb.getPage();
        int pageSize = ttb.getPageSize();
        String name = ttb.getCondition().get("name");
        String orderDate = ttb.getCondition().get("orderDate");
        boolean showReviewer = Boolean.parseBoolean(ttb.getCondition().get("showReviewer"));
        //如果是查询历史记录
        if (showReviewer){
            QueryWrapper<UserRecord> queryWrapper = new QueryWrapper<UserRecord>();
            //如果名称不为空则模糊查找名称
            if (StringUtils.isNotEmpty(name)) {
                queryWrapper.like("ur.username", name);
            }
            if (StringUtils.isNotEmpty(orderDate)) {
                queryWrapper.apply("date_format(ur.create_time,'%Y-%m-%d')={0}", orderDate);
            }
            //降序排序
            queryWrapper.orderByDesc("ur.update_time");
            Page<UserRecord> page = new Page<>(pageNum, pageSize);
            IPage<UserRecord> iPage = userRecordMapper.selectPageByCondition(page, queryWrapper);
            return PageUtil.pageResultCopy(iPage);
        }else {
            Page<UserRecord> page = new Page<>(pageNum, pageSize);
            IPage<UserRecord> userRecordIPage = userRecordMapper.lastRecord(page, name);
            return PageUtil.pageResultCopy(userRecordIPage);
        }
    }

    @Override
    public Boolean judgeOrder(String date) {
        if (ObjectUtils.isNotEmpty(date)) {
            QueryWrapper<UserRecord> queryWrapper = new QueryWrapper<>();
//            queryWrapper.apply("date_format(create_time,'%Y-%m-%d')={0}", date);
            Integer count = userRecordMapper.selectCount(queryWrapper);
            return count != null && count > 0;
        } else {
            throw new ServiceException("当天日期参数不能为空");
        }
    }

    @Override
    public void setOrder(String yearQuarter, String id) {
        if (ObjectUtils.isEmpty(id)) {
            return;
        }
        Drinks drinks = drinksMapper.selectById(id);
        if (ObjectUtils.isEmpty(drinks)) {
            if (log.isDebugEnabled()) {
                log.debug("-----系统没有该饮品-------drinkId:{}", id);
            }
            throw new ServiceException("系统没有该饮品");
        }
        Integer userCount = userMapper.selectCount(null);
        if (userCount != null && userCount == 0) {
            throw new ServiceException("设置失败，系统没有录入人员");
        }
        List<User> users = userMapper.selectList(null);
        List<UserRecord> userRecordList = users.stream().map(u -> new UserRecord(u.getId(), u.getName(), id, drinks.getName(), yearQuarter,drinks.getPrice())).collect(Collectors.toList());
        if (log.isDebugEnabled()) {
            log.debug("------批量插入点餐记录------：{}", JSON.toJSONString(userRecordList));
        }
        this.saveBatch(userRecordList);
    }

    @Override
    public void saveOrUpdateOrder(SaveOrUpdateDto saveOrUpdateDto) {
        if (ObjectUtils.isEmpty(saveOrUpdateDto)) {
            return;
        }
        String id = saveOrUpdateDto.getId();
        String userId = saveOrUpdateDto.getUserId();
        String userName = saveOrUpdateDto.getUsername();
        String drinkId = saveOrUpdateDto.getDrinkId();
        String drinkName = saveOrUpdateDto.getDrinkName();
        BigDecimal price = saveOrUpdateDto.getPrice();
        String yearQuarter = saveOrUpdateDto.getYearQuarter();
        //如果前端是通过输入名字的，不是通过下拉选择的，即系统之前没有录入的则执行插入用户表
        User user;
        if (ObjectUtils.isEmpty(userId)) {
            //如果名字相同则不新增，不相同则新增
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("name",userName);
            List<User> userList = userMapper.selectList(queryWrapper);
            if (userList.isEmpty()){
                user = new User(userName);
                userMapper.insert(user);
                userId = user.getId();
            }else {
                //如果当天
                QueryWrapper<UserRecord> query=new QueryWrapper<>();
                query.eq("username",userName);
                query.apply("date_format(create_time,'%Y-%m-%d')={0}", DateFormatUtils.format(new Date(),"yyyy-MM-dd"));
                UserRecord userRecord = userRecordMapper.selectOne(query);
                if (Objects.nonNull(userRecord)){
                    id=userRecord.getId();
                    userId = userList.get(0).getId();
                    userName=userList.get(0).getName();
                }
            }
        } else {
            user = userMapper.selectById(userId);
            if (ObjectUtils.isEmpty(user)) {
                if (log.isDebugEnabled()) {
                    log.debug("-----系统未找到人员--------User.id:{}", userId);
                }
                throw new ServiceException("系统未找到人员");
            }
        }
        //前端是输入饮品名的，不是通过下拉选择的，需要控制价格的必填且执行插入饮品类型表
        Drinks drinks;
        if (ObjectUtils.isEmpty(drinkId)) {
            if (ObjectUtils.isEmpty(price)) {
                throw new ServiceException("饮品价格没填，难道想白嫖？");
            }
            drinks = new Drinks(drinkName, price);
            drinksMapper.insert(drinks);
            drinkId = drinks.getId();
        } else {
            drinks = drinksMapper.selectById(drinkId);
            if (ObjectUtils.isEmpty(drinks)) {
                if (log.isDebugEnabled()) {
                    log.debug("-----系统未找到饮品--------Drink.id:{}", drinkId);
                }
                throw new ServiceException("系统未找到饮品");
            }
        }
        UserRecord userRecord;
        if (ObjectUtils.isNotEmpty(id)) {
            userRecord = userRecordMapper.selectById(id);
            if (ObjectUtils.isEmpty(userRecord)) {
                if (log.isDebugEnabled()) {
                    log.debug("-----点餐记录不存在--------UserRecord.id:{}", id);
                }
                throw new ServiceException("点餐记录不存在");
            }
            userRecord.setUserId(userId);
            userRecord.setUsername(userName);
            userRecord.setDrinkId(drinkId);
            userRecord.setDrinkName(drinkName);
            userRecord.setDrinkPrice(drinks.getPrice());
            userRecord.setYearQuarter(yearQuarter != null ? yearQuarter : userRecord.getYearQuarter());
        } else {
            userRecord = new UserRecord(userId, userName, drinkId, drinkName, yearQuarter,drinks.getPrice());
        }
        if (log.isDebugEnabled()) {
            log.debug("-----点餐记录--------{}", JSON.toJSONString(userRecord));
        }
        userRecord.setUpdateTime(null);
        this.saveOrUpdate(userRecord);

    }

    @Override
    public void deleteUserRecord(String id) {
        userRecordMapper.deleteById(id);
    }

    @Override
    public BigDecimal getAmountSpent(String yearAndQuarter) {
        return  userRecordMapper.getSpentBudget(yearAndQuarter);
    }
}
